<template>
  <div class="quick-functions">
    <div class="header">
      <div class="title">
        <i class="fa fa-bolt"></i>
        <span>快捷功能</span>
      </div>
      <div class="actions">
        <el-tooltip content="自定义功能" placement="top">
          <el-button circle size="small" @click="showCustomizeDialog">
            <i class="fa fa-cog"></i>
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <div class="function-list">
      <div 
        v-for="(item, index) in displayedFunctions.slice(0, maxDisplay)" 
        :key="index" 
        class="function-item" 
        @click="navigateTo(item.path)"
      >
        <div class="function-icon" :style="{ backgroundColor: item.color }">
          <i :class="item.icon"></i>
        </div>
        <div class="function-name">{{ item.name }}</div>
      </div>
      <div v-if="displayedFunctions.length > maxDisplay" class="function-item more" @click="showAllFunctions">
        <div class="function-icon" style="background-color: #909399">
          <i class="fa fa-ellipsis-h"></i>
        </div>
        <div class="function-name">更多</div>
      </div>
    </div>

    <!-- 自定义功能对话框 -->
    <el-dialog v-model="customizeDialogVisible" title="自定义快捷功能" width="650px">
      <el-tabs v-model="customizeTab">
        <el-tab-pane label="当前功能" name="current">
          <el-alert type="info" :closable="false" class="mb-3">
            拖拽可调整顺序，勾选显示在首页，最多显示{{ maxDisplay }}个
          </el-alert>
          <el-scrollbar height="300px">
            <draggable 
              v-model="draggableFunctions" 
              item-key="id"
              handle=".drag-handle"
              class="drag-list"
            >
              <template #item="{ element }">
                <div class="drag-item">
                  <div class="drag-handle">
                    <i class="fa fa-arrows-alt"></i>
                  </div>
                  <el-checkbox v-model="element.selected">
                    <div class="function-info">
                      <div class="function-item-icon" :style="{ backgroundColor: element.color }">
                        <i :class="element.icon"></i>
                      </div>
                      <span>{{ element.name }}</span>
                    </div>
                  </el-checkbox>
                  <div class="drag-actions">
                    <el-popover
                      placement="top-start"
                      title="编辑功能"
                      :width="230"
                      trigger="click"
                      v-model:visible="element.isEditing"
                    >
                      <template #reference>
                        <el-button type="text" size="small" @click="startEdit(element)">
                          <i class="fa fa-edit"></i>
                        </el-button>
                      </template>
                      <div class="edit-form">
                        <el-form label-position="top" :model="editingFunction" size="small">
                          <el-form-item label="名称">
                            <el-input v-model="editingFunction.name" />
                          </el-form-item>
                          <el-form-item label="颜色">
                            <el-color-picker v-model="editingFunction.color" />
                          </el-form-item>
                          <el-button type="primary" @click="saveEdit(element)">保存</el-button>
                        </el-form>
                      </div>
                    </el-popover>
                    <el-button 
                      type="text" 
                      size="small" 
                      @click="removeFunction(element)"
                      style="color: #f56c6c;"
                    >
                      <i class="fa fa-trash"></i>
                    </el-button>
                  </div>
                </div>
              </template>
            </draggable>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane label="添加功能" name="add">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索功能"
            prefix-icon="fa fa-search"
            clearable
            class="mb-3"
          />
          <el-scrollbar height="300px">
            <el-tree
              :data="menuTree"
              node-key="id"
              :filter-node-method="filterNode"
              ref="menuTreeRef"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <div class="tree-node-icon" v-if="data.icon" :style="{ backgroundColor: data.color || '#909399' }">
                    <i :class="data.icon"></i>
                  </div>
                  <span>{{ node.label }}</span>
                  <el-button
                    v-if="!isInFunctions(data) && !data.children"
                    class="add-btn"
                    circle
                    plain
                    size="small"
                    @click.stop="addFunction(data)"
                  >
                    <i class="fa fa-plus"></i>
                  </el-button>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="customizeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCustomFunctions">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更多功能对话框 -->
    <el-dialog v-model="allFunctionsDialogVisible" title="所有快捷功能" width="500px">
      <div class="all-functions-grid">
        <div 
          v-for="(item, index) in displayedFunctions" 
          :key="index" 
          class="all-function-item" 
          @click="navigateAndClose(item.path)"
        >
          <div class="function-icon" :style="{ backgroundColor: item.color }">
            <i :class="item.icon"></i>
          </div>
          <div class="function-name">{{ item.name }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watch, nextTick, inject } from 'vue'
import type { Ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ElTree } from 'element-plus'
// @ts-ignore
import draggable from 'vuedraggable'

interface FunctionItem {
  id: number;
  name: string;
  path: string;
  icon: string;
  color: string;
  selected: boolean;
  isEditing?: boolean;
}

// 使用 ElTree 的 TreeNodeData 接口
interface MenuNode {
  id: string;
  label?: string;
  name: string;
  path?: string;
  icon?: string;
  color?: string;
  children?: MenuNode[];
}

type FilterNodeMethodFunction = (value: string, data: any, node: any) => boolean;

export default defineComponent({
  name: 'QuickFunctions',
  components: {
    draggable
  },
  props: {
    maxDisplay: {
      type: Number,
      default: 7
    }
  },
  setup(props) {
    // 从父组件注入导航方法
    const navigateTo = inject('navigateTo') as (path: string) => void;

    // 快捷功能列表
    const allFunctions = ref<FunctionItem[]>([
      { id: 1, name: '新建销售订单', path: '/yxerp/sales/order/create', icon: 'fa fa-file-text', color: '#409EFF', selected: true },
      { id: 2, name: '库存查询', path: '/yxerp/inventory/stock', icon: 'fa fa-cubes', color: '#E6A23C', selected: true },
      { id: 3, name: '采购申请', path: '/yxerp/purchase/requisition', icon: 'fa fa-shopping-cart', color: '#67C23A', selected: true },
      { id: 4, name: '生产计划', path: '/yxerp/production/plan', icon: 'fa fa-industry', color: '#F56C6C', selected: true },
      { id: 5, name: 'POS零售', path: '/yxerp/retail/pos', icon: 'fa fa-calculator', color: '#9966FF', selected: true },
      { id: 6, name: '客户管理', path: '/yxerp/master/customer', icon: 'fa fa-users', color: '#19BE6B', selected: true },
      { id: 7, name: '财务收款', path: '/yxerp/finance/receipt', icon: 'fa fa-money', color: '#FF9900', selected: true },
      { id: 8, name: '发货管理', path: '/yxerp/logistics/delivery', icon: 'fa fa-truck', color: '#0099CC', selected: false },
      { id: 9, name: '收货管理', path: '/yxerp/logistics/receipt', icon: 'fa fa-sign-in', color: '#FF6666', selected: false },
      { id: 10, name: '产品管理', path: '/yxerp/master/product', icon: 'fa fa-cube', color: '#6633CC', selected: false }
    ]);

    // 显示的功能
    const displayedFunctions = computed(() => {
      return allFunctions.value.filter(item => item.selected);
    });

    // 拖拽排序的功能列表
    const draggableFunctions = ref<FunctionItem[]>([]);

    // 编辑状态的功能
    const editingFunction = ref({
      name: '',
      color: ''
    });

    // 对话框控制
    const customizeDialogVisible = ref(false);
    const allFunctionsDialogVisible = ref(false);
    const customizeTab = ref('current');
    const searchKeyword = ref('');
    const menuTreeRef = ref<InstanceType<typeof ElTree> | null>(null);

    // 修复树节点数据，添加label属性
    const processMenuNodes = (nodes: MenuNode[]): MenuNode[] => {
      return nodes.map(node => {
        const newNode = { ...node, label: node.name };
        if (node.children && node.children.length > 0) {
          newNode.children = processMenuNodes(node.children);
        }
        return newNode;
      });
    };

    // 菜单树数据（示例数据，实际应该从API获取）
    const rawMenuTree = ref<MenuNode[]>([
      {
        id: 'sales',
        name: '销售管理',
        icon: 'fa fa-shopping-bag',
        color: '#409EFF',
        children: [
          { id: 'sales-order', name: '销售订单', path: '/yxerp/sales/order', icon: 'fa fa-file-text', color: '#409EFF' },
          { id: 'sales-quotation', name: '销售报价', path: '/yxerp/sales/quotation', icon: 'fa fa-file', color: '#409EFF' },
          { id: 'sales-delivery', name: '销售发货', path: '/yxerp/sales/delivery', icon: 'fa fa-truck', color: '#409EFF' },
          { id: 'sales-return', name: '销售退货', path: '/yxerp/sales/return', icon: 'fa fa-reply', color: '#409EFF' },
          { id: 'sales-report', name: '销售报表', path: '/yxerp/sales/report', icon: 'fa fa-bar-chart', color: '#409EFF' }
        ]
      },
      {
        id: 'purchase',
        name: '采购管理',
        icon: 'fa fa-shopping-cart',
        color: '#67C23A',
        children: [
          { id: 'purchase-order', name: '采购订单', path: '/yxerp/purchase/order', icon: 'fa fa-file-text', color: '#67C23A' },
          { id: 'purchase-requisition', name: '采购申请', path: '/yxerp/purchase/requisition', icon: 'fa fa-file', color: '#67C23A' },
          { id: 'purchase-receipt', name: '采购收货', path: '/yxerp/purchase/receipt', icon: 'fa fa-sign-in', color: '#67C23A' },
          { id: 'purchase-return', name: '采购退货', path: '/yxerp/purchase/return', icon: 'fa fa-reply', color: '#67C23A' },
          { id: 'purchase-report', name: '采购报表', path: '/yxerp/purchase/report', icon: 'fa fa-bar-chart', color: '#67C23A' }
        ]
      },
      {
        id: 'inventory',
        name: '库存管理',
        icon: 'fa fa-cubes',
        color: '#E6A23C',
        children: [
          { id: 'inventory-stock', name: '库存查询', path: '/yxerp/inventory/stock', icon: 'fa fa-search', color: '#E6A23C' },
          { id: 'inventory-inbound', name: '入库单', path: '/yxerp/inventory/inbound', icon: 'fa fa-sign-in', color: '#E6A23C' },
          { id: 'inventory-outbound', name: '出库单', path: '/yxerp/inventory/outbound', icon: 'fa fa-sign-out', color: '#E6A23C' },
          { id: 'inventory-transfer', name: '库存调拨', path: '/yxerp/inventory/transfer', icon: 'fa fa-exchange', color: '#E6A23C' },
          { id: 'inventory-check', name: '库存盘点', path: '/yxerp/inventory/check', icon: 'fa fa-check-square', color: '#E6A23C' }
        ]
      },
      {
        id: 'production',
        name: '生产管理',
        icon: 'fa fa-industry',
        color: '#F56C6C',
        children: [
          { id: 'production-plan', name: '生产计划', path: '/yxerp/production/plan', icon: 'fa fa-calendar', color: '#F56C6C' },
          { id: 'production-order', name: '生产订单', path: '/yxerp/production/order', icon: 'fa fa-file-text', color: '#F56C6C' },
          { id: 'production-task', name: '生产任务', path: '/yxerp/production/task', icon: 'fa fa-tasks', color: '#F56C6C' },
          { id: 'production-bom', name: '物料清单', path: '/yxerp/production/bom', icon: 'fa fa-list', color: '#F56C6C' },
          { id: 'production-cost', name: '生产成本', path: '/yxerp/production/cost', icon: 'fa fa-money', color: '#F56C6C' }
        ]
      },
      {
        id: 'retail',
        name: '零售管理',
        icon: 'fa fa-shopping-basket',
        color: '#9966FF',
        children: [
          { id: 'retail-pos', name: 'POS零售', path: '/yxerp/retail/pos', icon: 'fa fa-calculator', color: '#9966FF' },
          { id: 'retail-member', name: '会员管理', path: '/yxerp/retail/member', icon: 'fa fa-vcard', color: '#9966FF' },
          { id: 'retail-promotion', name: '促销活动', path: '/yxerp/retail/promotion', icon: 'fa fa-gift', color: '#9966FF' },
          { id: 'retail-report', name: '零售报表', path: '/yxerp/retail/report', icon: 'fa fa-bar-chart', color: '#9966FF' }
        ]
      }
    ]);

    // 为树节点添加label属性
    const menuTree = computed(() => {
      return processMenuNodes(rawMenuTree.value);
    });

    // 初始化拖拽列表
    watch(() => customizeDialogVisible.value, (newVal) => {
      if (newVal) {
        draggableFunctions.value = JSON.parse(JSON.stringify(allFunctions.value));
      }
    });

    // 搜索过滤
    watch(() => searchKeyword.value, (val) => {
      nextTick(() => {
        if (menuTreeRef.value) {
          menuTreeRef.value.filter(val);
        }
      });
    });

    // 过滤节点方法
    const filterNode: FilterNodeMethodFunction = (value, data) => {
      if (!value) return true;
      return data.name.toLowerCase().includes(value.toLowerCase());
    };

    // 检查是否已在快捷功能中
    const isInFunctions = (item: MenuNode) => {
      return allFunctions.value.some(func => func.path === item.path);
    };

    // 开始编辑
    const startEdit = (item: FunctionItem) => {
      editingFunction.value.name = item.name;
      editingFunction.value.color = item.color;
      item.isEditing = true;
    };

    // 保存编辑
    const saveEdit = (item: FunctionItem) => {
      item.name = editingFunction.value.name;
      item.color = editingFunction.value.color;
      item.isEditing = false;
      ElMessage.success('编辑成功');
    };

    // 添加到快捷功能
    const addFunction = (item: MenuNode) => {
      if (isInFunctions(item)) {
        ElMessage.warning('该功能已在快捷功能列表中');
        return;
      }
      
      if (!item.path) {
        ElMessage.warning('该菜单项没有关联的路径');
        return;
      }
      
      const newFunction: FunctionItem = {
        id: Date.now(),
        name: item.name,
        path: item.path,
        icon: item.icon || 'fa fa-link',
        color: item.color || '#909399',
        selected: true
      };
      
      allFunctions.value.push(newFunction);
      draggableFunctions.value.push(JSON.parse(JSON.stringify(newFunction)));
      
      ElMessage.success(`"${item.name}"已添加到快捷功能`);
    };

    // 移除功能
    const removeFunction = (item: FunctionItem) => {
      const index = allFunctions.value.findIndex(f => f.id === item.id);
      if (index !== -1) {
        allFunctions.value.splice(index, 1);
        draggableFunctions.value = draggableFunctions.value.filter(f => f.id !== item.id);
        ElMessage.success('已从快捷功能中移除');
      }
    };

    // 处理树节点点击
    const handleNodeClick = (data: MenuNode) => {
      // 如果有子节点，不做任何操作
      if (data.children && data.children.length) {
        return;
      }
      
      // 如果是叶子节点且有路径，添加到快捷功能
      if (data.path) {
        addFunction(data);
      }
    };

    // 显示自定义对话框
    const showCustomizeDialog = () => {
      customizeDialogVisible.value = true;
      customizeTab.value = 'current';
    };

    // 显示所有功能对话框
    const showAllFunctions = () => {
      allFunctionsDialogVisible.value = true;
    };

    // 导航并关闭对话框
    const navigateAndClose = (path: string) => {
      navigateTo(path);
      allFunctionsDialogVisible.value = false;
    };

    // 保存自定义功能设置
    const saveCustomFunctions = () => {
      // 更新所有功能列表的顺序和选中状态
      allFunctions.value = JSON.parse(JSON.stringify(draggableFunctions.value));
      
      customizeDialogVisible.value = false;
      ElMessage.success('快捷功能已更新');
      
      // 实际应用中，应该调用API保存用户设置
      // saveUserQuickFunctions(allFunctions.value);
    };

    return {
      allFunctions,
      displayedFunctions,
      draggableFunctions,
      editingFunction,
      customizeDialogVisible,
      allFunctionsDialogVisible,
      customizeTab,
      searchKeyword,
      menuTreeRef,
      menuTree,
      filterNode,
      isInFunctions,
      startEdit,
      saveEdit,
      addFunction,
      removeFunction,
      handleNodeClick,
      showCustomizeDialog,
      showAllFunctions,
      navigateAndClose,
      saveCustomFunctions,
      navigateTo
    };
  }
});
</script>

<style scoped lang="scss">
.quick-functions {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    border-bottom: 1px solid #ebeef5;
    
    .title {
      display: flex;
      align-items: center;
      
      i {
        font-size: 16px;
        color: #409EFF;
        margin-right: 8px;
      }
      
      span {
        font-size: 15px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
  
  .function-list {
    display: flex;
    flex-wrap: wrap;
    padding: 15px;
    gap: 10px;
    
    .function-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 80px;
      cursor: pointer;
      transition: all 0.2s;
      padding: 8px 0;
      border-radius: 4px;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      .function-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 8px;
        margin-bottom: 8px;
        color: white;
        font-size: 18px;
      }
      
      .function-name {
        font-size: 12px;
        color: #606266;
        text-align: center;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      &.more {
        .function-icon {
          font-size: 16px;
        }
      }
    }
  }
  
  // 自定义对话框样式
  .drag-list {
    .drag-item {
      display: flex;
      align-items: center;
      padding: 10px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      margin-bottom: 10px;
      background-color: white;
      
      .drag-handle {
        cursor: move;
        padding: 0 10px;
        color: #909399;
      }
      
      .function-info {
        display: flex;
        align-items: center;
        
        .function-item-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          border-radius: 4px;
          margin-right: 10px;
          color: white;
          font-size: 14px;
        }
      }
      
      .drag-actions {
        margin-left: auto;
        display: flex;
        gap: 5px;
      }
    }
  }
  
  .tree-node {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 5px 0;
    
    .tree-node-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;
      border-radius: 4px;
      margin-right: 8px;
      color: white;
      font-size: 14px;
    }
    
    .add-btn {
      margin-left: auto;
    }
  }
  
  .all-functions-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
    
    .all-function-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      transition: all 0.2s;
      padding: 10px;
      border-radius: 4px;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      .function-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 8px;
        margin-bottom: 8px;
        color: white;
        font-size: 18px;
      }
      
      .function-name {
        font-size: 12px;
        color: #606266;
        text-align: center;
      }
    }
  }
  
  .edit-form {
    padding: 5px;
  }
  
  .mb-3 {
    margin-bottom: 15px;
  }
}
</style> 